package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.CodeVO;
import com.asktgapp.model.RegisterVo;
import com.asktgapp.user.activity.MainActivity;
import com.asktgapp.utils.MCountDownTimer;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/2/7
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description: 三方登录绑定手机
 */

public class RegisterNowFragment extends BaseFragment {

    @InjectView(R.id.iv_eye1)
    ImageView mEye;
    @InjectView(R.id.iv_eye2)
    ImageView mEye_;
    @InjectView(R.id.tv_send_code)
    TextView mSendCodeTV;
    @InjectView(R.id.et_phone)
    EditText mPhone;
    @InjectView(R.id.et_pwd)
    EditText mPwdET;
    @InjectView(R.id.et_pwd_)
    EditText mPwdET_;
    @InjectView(R.id.et_code)
    EditText mCodeET;
    @InjectView(R.id.tv_commit)
    TextView mCommit;

    private boolean isHide = true;
    private boolean isHide_ = true;
    private TimeCount time;
    private String userid;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_find_password, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        userid = getActivity().getIntent().getStringExtra("userid");
        mSendCodeTV.setOnClickListener(this);
        mCommit.setOnClickListener(this);
        mEye.setOnClickListener(this);
        mEye_.setOnClickListener(this);
        time = new TimeCount(60000, 1000);
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_send_code:
                sendCode();
                break;
            case R.id.iv_eye1:

                String pwd = mPwdET.getText().toString().trim();
                ;
                if (!Util.isEmpty(pwd)) {
                    if (isHide) {
                        mPwdET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        mEye.setImageResource(R.mipmap.ico_zhengyan);
                    } else {
                        mPwdET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        mEye.setImageResource(R.mipmap.ico_biiyan);
                    }
                    mPwdET.setSelection(pwd.length());
                    isHide = !isHide;
                }
                break;
            case R.id.iv_eye2:
                String pwd_ = mPwdET_.getText().toString().trim();

                if (!Util.isEmpty(pwd_)) {
                    if (isHide_) {
                        mPwdET_.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        mEye_.setImageResource(R.mipmap.ico_zhengyan);
                    } else {
                        mPwdET_.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        mEye_.setImageResource(R.mipmap.ico_biiyan);
                    }
                    mPwdET_.setSelection(pwd_.length());
                    isHide_ = !isHide_;
                }
                break;
            case R.id.tv_commit:
                commit();
                break;
        }
    }


    /**
     * 调用接口，发送验证码
     */
    private void sendCode() {
        String phone = mPhone.getText().toString().trim();
        if (Util.isEmpty(phone)) {
            showTost("请输入电话号码", 0);
            return;
        }
        sendCode(phone);
    }

    /**
     * 提交
     */
    private void commit() {
        String phone = mPhone.getText().toString().trim();
        String pwd = mPwdET.getText().toString().trim();
        String pwd_ = mPwdET_.getText().toString().trim();
        String code = mCodeET.getText().toString().trim();
        if (Util.isEmpty(phone)) {
            showTost("请输入电话号码", 0);
            return;
        }
        if (Util.isEmpty(pwd)) {
            showTost("请输入密码", 0);
            return;
        }
        if (Util.isEmpty(pwd_)) {
            showTost("请确认密码", 0);
            return;
        }
        if (!pwd.equals(pwd_)) {
            showTost("两次输入的密码不一致", 1);
            return;
        }
        if (Util.isEmpty(code)) {
            showTost("请输入验证码", 0);
            return;
        }
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("is_existence", 1);
        params.put("phone", phone);
        params.put("password", pwd);
        params.put("code", code);
        params.put("userid", userid);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<RegisterVo>> call = apiservice.bindPhone(params);
        call.enqueue(new Callback<ApiResponseBody<RegisterVo>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<RegisterVo>> call, Response<ApiResponseBody<RegisterVo>> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    RegisterVo bean = response.body().getResult();
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.USER_ID, bean.getId());
                    PreferencesUtil.putInt(getActivity(), PreferencesUtil.IS_SHOW_AUTH_DOOR, bean.getIsShow());
                    if (bean.getIsEngineer() == 1) {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, true);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_HX_ID, bean.getHuanxinId());
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, bean.getRealname() + "");

                    } else {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, false);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, bean.getUsername() + "");

                    }
//                    PreferencesUtil.putInt(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, bean.getIsEngineer());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.HEAD_IMG, bean.getUserPic());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_PASSWORD, bean.getPassword());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_PHONE, bean.getPhone());

//                    upToken();
                    startActivity(new Intent(getActivity(), MainActivity.class));
                    //TODO 考虑发送事件消息 通知loginfragment finish
                    getActivity().finish();
                } else {
                    showTost(response.raw().message(), 0);
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.USER_ID, "");
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<RegisterVo>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.USER_ID, "");
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    private void sendCode(String phone) {
        hideSoftKeyboard();
        if (!Util.isMobileNO(phone)) {
            showTost("手机号码格式错误", 0);
            return;
        }
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("phone", phone);
        params.put("type", 0);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<CodeVO>> call = apiservice.sendCode(params);
        call.enqueue(new Callback<ApiResponseBody<CodeVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<CodeVO>> call, Response<ApiResponseBody<CodeVO>> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    CodeVO bean = response.body().getResult();
//                    mCodeET.setText(String.valueOf(bean.getCode()));
                    showTost("验证码已发送", 1);
                    time.start();
                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<CodeVO>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 0);
            }
        });


    }


    class TimeCount extends MCountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (mSendCodeTV == null)
                return;

            mSendCodeTV.setText("发送验证码");
            // mSendCode.setTextColor(Color.parseColor("#40a540"));
            mSendCodeTV.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            if (mSendCodeTV == null)
                return;
            mSendCodeTV.setClickable(false);
            if (millisUntilFinished < 1000)
                mSendCodeTV.setText("发送验证码");
            else
                mSendCodeTV.setText(millisUntilFinished / 1000 + "秒后重发");
        }
    }

    private void upToken() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("ymToken", MyApplication.UmengToken);
        Call<ApiResponseBody> call = apiservice.updatePushToken(params);
        call.enqueue(new Callback<ApiResponseBody>() {
                         @Override
                         public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                             if (response.isSuccessful()) {
                                 Log.i("login", "token上传成功！");
                                 startActivity(new Intent(getActivity(), MainActivity.class));
                                 getActivity().finish();
                             } else {
                                 showTost(response.raw().message(), 0);
                             }
                         }

                         @Override
                         public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                             Log.i("login", "token上传失败！");
                         }
                     }
        );

    }
}
